package caidan.net;

import jinyilw.swing.image.ThumbMaker;
import jinyilw.tools.net.ClientTools;
import jinyilw.tools.net.NetConfig;
import jinyilw.tools.net.dev.CommandPacket;
import jinyilw.tools.net.file.FileTransfer;

import java.io.File;
import java.util.ArrayList;

public class NewFoodPanel extends AbstractNewFoodPanel
{
	private static final long serialVersionUID = -8424692830726670977L;
	private ArrayList<CommandPacket> allNewFoodDatas;
	private ClientTools clientTools;
	private boolean isConnected;
	private Object lock = new Object();

	public NewFoodPanel(ClientTools tools)
	{
		clientTools = tools;
		allNewFoodDatas = new ArrayList<>();
	}

	public void initNet()
	{
		clientTools.startFileTransferClient(NetConfig.fileServerPort,
				netNewFoodFolder, localNewFoodFolder);
		clientTools.addReceivePacketOperator((Object o) ->
		{
			if (o instanceof CommandPacket)
			{
				CommandPacket packet = (CommandPacket) o;
				int command = packet.getCommandID();
				// System.out.println("Command.S:" + command);
				if (command == Command.S.sendNewFoodToNet)
					new Thread(() ->
					{
						addNewFoodFromNet(packet);
					}).start();
				else if (command == Command.S.deleteNewFoodInNet)
					new Thread(() ->
					{
						netDeleteNewFood(packet);
					}).start();
				else if (command == Command.S.sendAllNewFoodToClient)
					allNewFoodDatas.add(packet);
				else if (command == Command.S.endSendAllNewFood)
					synchronized (lock)
					{
						lock.notifyAll();
					}
				;
			}
		});
		reloadFromNet();
		clientTools.addReConnectRunner(() ->
		{
			reloadFromNet();
		});
		clientTools.addBrokenRunner(() ->
		{
			isConnected = false;
			for (NewFoodLabel label : newFoodLabels)
				label.updateTitle();
		});
	}

	public void getAllNewFoodFromNet()
	{
		if (!isConnected)
			return;
		allNewFoodDatas.clear();
		sendCommandToNet(new CommandPacket(true), Command.C.getAllNewFood);
		synchronized (lock)
		{
			try
			{
				lock.wait(20000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		// System.out.println("notify");
		int i = 0, size = newFoodLabels.size();
		NewFoodLabel label;
		for (CommandPacket foodData : allNewFoodDatas)
		{
			if (i < size)
			{
				label = newFoodLabels.get(i);
				label.setLabel(foodData, true, false);
			} else
			{
				label = new NewFoodLabel(foodData, true);
				newFoodLabels.add(label);
			}
			i++;
		}

		if (i < size)
			for (int j = size - 1; j >= i; j--)
				newFoodLabels.remove(j);

		new Thread(() ->
		{
			for (NewFoodLabel foodLabel : newFoodLabels)
				foodLabel.getNetFiles();
		}).start();
	}

	// @Override
	public void addNewFoodFromNet(CommandPacket foodData)
	{
		addNewFoodLabel(new NewFoodLabel(foodData, true));
	}

	// @Override
	public void netDeleteNewFood(CommandPacket foodData)
	{
		NewFoodLabel label = getNetLabel(foodData.getLongData(),
				foodData.getDoubleData());
		if (label != null)
		{
			removeNewFoodLabel(label);
			label.forceDeleteFile();
			return;
		}
		String[] fileNames = foodData.getStringArr();
		File imageFile = new File(netNewFoodFolder, fileNames[0]);
		imageFile.delete();
		ThumbMaker.getDefaultThumbFile(imageFile).delete();
		new File(netNewFoodFolder, fileNames[1]).delete();
	}

	//	public void getFiles(CommandPacket foodData)
	//	{
	//		NewFoodLabel label = getNetLabel(foodData.getLongData(),
	//				foodData.getDoubleData());
	//		if (label == null)
	//			return;
	//		String ip = clientTools.getServerIP();
	//		int port = foodData.getIntData();
	//		try
	//		{
	//			Thread.sleep(200);
	//		} catch (InterruptedException e)
	//		{
	//			e.printStackTrace();
	//		}
	//		File[] files = TransferTools.receiveFilesFromNetTemporarily(ip, port,
	//				netNewFoodForder);
	//		if (files != null)
	//		{
	//			label.setImageFile(files[0]);
	//			label.setMakeFile(files[1]);
	//		}
	//	}

	private NewFoodLabel getNetLabel(long longData, double doubleData)
	{
		for (NewFoodLabel label : newFoodLabels)
			if (longData == label.foodData.getLongData()
					&& doubleData == label.foodData.getDoubleData())
				return label;
		return null;
	}

	//	private NewFoodLabel getLocalLabel(long longData, double doubleData)
	//	{
	//		for (NewFoodLabel label : localLabels)
	//			if (longData == label.foodData.getLongData()
	//					&& doubleData == label.foodData.getDoubleData())
	//				return label;
	//		return null;
	//	}

	private boolean isFristOpen = true;
	synchronized void reloadFromNet()
	{
		isConnected = clientTools.isConnected();
		if (!isConnected && !isFristOpen)
			return;
		contentPanel.removeAll();
		getAllNewFoodFromNet();
		if (isFristOpen)
		{
			readFromFile();
			isFristOpen = false;
		}
		for (NewFoodLabel label : newFoodLabels)
			contentPanel.add(label);
		for (NewFoodLabel label : localLabels)
			contentPanel.add(label);
		revalidate();
		repaint();
	}

	@Override
	public boolean sendCommandToNet(CommandPacket commandPacket, int command)
	{
		return clientTools.sendCommand(commandPacket, command);
	}

	@Override
	public boolean isConnected()
	{
		return isConnected;
	}
	@Override
	public boolean isClient()
	{
		return true;
	}
	@Override
	public String getDataFolderPath()
	{
		return "clientData";
	}
	@Override
	public String getNewFoodFolderPath()
	{
		return "clientNewFood";
	}

	@Override
	public FileTransfer getFileTransfer()
	{
		return clientTools.getFileTransferClient();
	}
}
